#!/bin/bash

_write_AppRun(){
	echo "#!/bin/sh"
	echo 'SELF=$(readlink -f "$0")'
	echo 'HERE=${SELF%/*}'
	echo 'export PATH="${HERE}/usr/bin/:${HERE}/usr/sbin/:${HERE}/usr/games/:${HERE}/bin/:${HERE}/sbin/${PATH:+:$PATH}"'
	echo 'export LD_LIBRARY_PATH="${HERE}/usr/lib/:${HERE}/usr/lib/i386-linux-gnu/:${HERE}/usr/lib/x86_64-linux-gnu/:${HERE}/usr/lib32/:${HERE}/usr/lib64/:${HERE}/lib/:${HERE}/lib/i386-linux-gnu/:${HERE}/lib/x86_64-linux-gnu/:${HERE}/lib32/:${HERE}/lib64/${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"'
	echo 'export PYTHONPATH="${HERE}/usr/share/pyshared/${PYTHONPATH:+:$PYTHONPATH}"'
	echo 'export XDG_DATA_DIRS="${HERE}/usr/share/${XDG_DATA_DIRS:+:$XDG_DATA_DIRS}"'
	echo 'export PERLLIB="${HERE}/usr/share/perl5/:${HERE}/usr/lib/perl5/${PERLLIB:+:$PERLLIB}"'
	echo 'export GSETTINGS_SCHEMA_DIR="${HERE}/usr/share/glib-2.0/schemas/${GSETTINGS_SCHEMA_DIR:+:$GSETTINGS_SCHEMA_DIR}"'
	echo 'export QT_PLUGIN_PATH="${HERE}/usr/lib/qt4/plugins/:${HERE}/usr/lib/i386-linux-gnu/qt4/plugins/:${HERE}/usr/lib/x86_64-linux-gnu/qt4/plugins/:${HERE}/usr/lib32/qt4/plugins/:${HERE}/usr/lib64/qt4/plugins/:${HERE}/usr/lib/qt5/plugins/:${HERE}/usr/lib/i386-linux-gnu/qt5/plugins/:${HERE}/usr/lib/x86_64-linux-gnu/qt5/plugins/:${HERE}/usr/lib32/qt5/plugins/:${HERE}/usr/lib64/qt5/plugins/${QT_PLUGIN_PATH:+:$QT_PLUGIN_PATH}"'
	echo 'EXEC=$(grep -e "^Exec=.*" "${HERE}"/*.desktop | head -n 1 | cut -d "=" -f 2 | cut -d " " -f 1)'
	echo 'exec "${EXEC}" "$@"'
}

_write_desktop(){
echo "[Desktop Entry]"
echo "Type=Application"
echo "Name=$name"
[ "$executable" == "" ] && export executable=$name
echo "Exec=$executable"
echo "Comment=$summary"
[ "$icon" == "" ] && export icon=$name
echo "Icon=$name"
if [ "$categories" == "" ] ; then
	echo "Categories=$categories"
fi
echo "Terminal=false"

}

copy_library(){
while read stuff
do
	ldd $stuff | grep "=>" | awk '{print $3}' | while read line
	do
		if [ -f $line ] ; then
			mkdir -p "$PKGDIR"/$line || true
			rmdir "$PKGDIR"/$line || true
			cat $line > $PKGDIR/$line || true
			cat $(readlink -f $line) > $PKGDIR/$(readlink -f $line)
			chmod +x "$PKGDIR/$line"
		fi
	done
done
}

_create_metadata(){
	cd $PKGDIR
	_write_AppRun > $PKGDIR/AppRun
	chmod +x $PKGDIR/AppRun
	_write_desktop > $PKGDIR/$name.desktop
	touch $PKGDIR/$name.png
}
_package(){
	# checking appimagekit
	if [ ! -f ~/.appimagekit ] ; then
		wget -c https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-$(uname -m).AppImage -O ~/.appimagekit
		chmod +x ~/.appimagekit
	fi
	cp -prfv "$INSTALLDIR"/* "$PKGDIR"/
	[ "${PORTABLE}" == "true" ] && find $INSTALLDIR | copy_library &> /dev/null || true
	cd $CURDIR
	ARCH=$(uname -m) ~/.appimagekit "$PKGDIR"
}
